#!/bin/bash
echo "Building AI Communication System..."
echo

# 设置编译参数
WXWIN="/d/vc/wxWidgets-3.2.7"
CXX="g++"
CXXFLAGS="-std=c++11 -O2 -Wall -Wextra -D__WXMSW__ -D_UNICODE -DUNICODE"
INCLUDES="-I$WXWIN/include -I$WXWIN/include/msvc -I./src -I./lib -I./lib/tinyxml"
LIBS="-L$WXWIN/lib/gcc_x64_dll"
LIBRARIES="-lwxmsw32u_core -lwxbase32u -lwxmsw32u_adv -lwxbase32u_xml -lwxpng -lwxzlib"

# 源文件列表
SOURCES=(
    "lib/stlconfig.cpp"
    "lib/stlconvert.cpp" 
    "lib/stlfutils.cpp"
    "lib/stlgpm.cpp"
    "lib/stlstrings.cpp"
    "lib/stlvariables.cpp"
    "lib/stringhash.cpp"
    "lib/tinyxml/tinystr.cpp"
    "lib/tinyxml/tinyxml.cpp"
    "lib/tinyxml/tinyxmlerror.cpp"
    "lib/tinyxml/tinyxmlparser.cpp"
    "src/buildtools.cpp"
    "src/cbbuildcfg.cpp"
    "src/cbbuildmgr.cpp"
    "src/cbglobalvar.cpp"
    "src/cbhelper.cpp"
    "src/cbproject.cpp"
    "src/cbptarget.cpp"
    "src/cbpunit.cpp"
    "src/cbworkspace.cpp"
    "src/depsearch.cpp"
    "src/makefile.cpp"
    "src/platforms.cpp"
    "src/toolchains.cpp"
    "src/aicoder_enhancements.cpp"
    # AI 通信系统文件
    "src/ai_communication_protocol.cpp"
    "src/ai_terminal.cpp"
    "src/human_ai_terminal.cpp"
    "src/ai_computer_terminal.cpp"
    "src/ai_message_router.cpp"
    "src/ai_system_controller.cpp"
    "src/cbp2make_ai_complete.cpp"
)

# 创建构建目录
mkdir -p bin
mkdir -p .objs/wx32_64

echo "Compiling ${#SOURCES[@]} source files..."

# 编译所有源文件
OBJECT_FILES=()
for source in "${SOURCES[@]}"; do
    if [[ ! -f "$source" ]]; then
        echo "❌ Source file not found: $source"
        continue
    fi
    
    object_file=".objs/wx32_64/$(basename "$source" .cpp).o"
    OBJECT_FILES+=("$object_file")
    
    echo "🔨 Compiling: $source"
    $CXX $CXXFLAGS $INCLUDES -c "$source" -o "$object_file"
    
    if [[ $? -ne 0 ]]; then
        echo "❌ Compilation failed: $source"
        exit 1
    fi
done

echo "Linking executable..."

# 链接可执行文件
$CXX $CXXFLAGS -o "bin/cbp2make_ai_wx32_64.exe" "${OBJECT_FILES[@]}" $LIBS $LIBRARIES \
    -lkernel32 -luser32 -lgdi32 -lwinspool -lcomdlg32 \
    -ladvapi32 -lshell32 -lole32 -loleaut32 -luuid \
    -lcomctl32 -lrpcrt4 -loleacc -luxtheme

if [[ $? -eq 0 ]]; then
    echo "✅ Build successful!"
    echo "📦 Executable: bin/cbp2make_ai_wx32_64.exe"
    ls -lh "bin/cbp2make_ai_wx32_64.exe"
else
    echo "❌ Linking failed!"
    exit 1
fi
